#!/usr/bin/perl

require LWP::UserAgent;
use HTTP::Request::Common;
use Archive::Zip qw ( :ERROR_CODES :CONSTANTS );
use Digest::MD5 qw( md5 md5_hex md5_base64 );
use File::stat;
use File::Basename;

my $exec_dir = dirname $0;
%::http_passwords = ();
my $current_realm;
{
    package RequestAgent;
    @ISA = qw(LWP::UserAgent);

    sub new
    { 
	my $self = LWP::UserAgent::new(@_);
	$self->agent("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12");
	$self->timeout(30);
	$self->env_proxy;
	$self->cookie_jar({ file =>"$ENV{HOME}/.cookies.txt", autosave => 1 });
	$self;
    }
}

my $repo       = "baen_books";
my $zip_dir  = "$repo/zips";

opendir(DIR, $zip_dir) || die "can't opendir $zip_dir: $!";
my @files = grep { /\.zip$/ && -f "$zip_dir/$_" } readdir(DIR);
closedir DIR;

my $ua = RequestAgent->new;

my $filesize_mismatch = 0;

foreach my $file (@files) {
    # Verify the size of the zip.  If any of them fail, then 
    # Blow it away and start again.
    $file =~ /([^._]+)_([^._]*)\.zip/;
my $SKU = $1;
my $ID = $2;
#print "$SKU -> $ID\n";

    # O.k. now download the file size and verify it.
$baen_url = "http://www.baen.com/library/$SKU/H$SKU.zip";
$webscription_url = "http://www.webscription.net/SendZip.aspx?SKU=$SKU&ProductID=$ID&format=H";

my $zip_url = $webscription_url;
if ($ID == "" || ! defined $ID) {
    $zip_url = $baen_url;
}

my $sb = stat("$zip_dir/$file");
my $size = $sb->size;

#print "$file...",$size,"\n";
#print "$zip_url\n";
#print ".";
my $request = GET($zip_url);
my $res = $ua->simple_request($request, sub {
    my( $data, $response, $proto ) = @_;
    my $content_length = $response->header('content-length') || 1;
    
    if ($content_length != $size) {
	print "$file : Sizes don't match, removing\n";
	$filesize_mismatch = 1;
	unlink "$zip_dir/$file";
    }
    die();
});
}

if ($filesize_mismatch == 1) {
    print "Forcing rebuild\n";
    system("$exec_dir/create_baen_plists");
    system("$exec_dir/build_baen_index.pl");
}
